<?php

namespace App\Repository;

use App\Entity\NoticeType;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;

/**
 * @method NoticeType|null find($id, $lockMode = null, $lockVersion = null)
 * @method NoticeType|null findOneBy(array $criteria, array $orderBy = null)
 * @method NoticeType[]    findAll()
 * @method NoticeType[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class NoticeTypeRepository extends ServiceEntityRepository {
    protected $cache;

    public function __construct (ManagerRegistry $registry, CacheInterface $cache) {
        parent::__construct($registry, NoticeType::class);
        $this->cache = $cache;
    }

    /**
     * 返回数组集合数据 key-value 形式
     * @return mixed
     * @throws \Psr\Cache\InvalidArgumentException
     */
    public function findAllToArrayOne () {
        return $this->cache->get('notice_type_get_array_result_one', function (ItemInterface $item) {
            $item->expiresAfter(600);
            $result = [];
            $objs = $this->findBy(['status' => true]);
            foreach ($objs as $obj) {
                $result[$obj->getId()] = $obj->getTitle();
            }
            return $result;
        }, 1.0);
    }

    /**
     * 返回数组集合数据 item 形式
     * @return mixed
     * @throws \Psr\Cache\InvalidArgumentException
     */
    public function findAllToArrayTwo () {
        return $this->cache->get('notice_type_get_array_result_two', function (ItemInterface $item) {
            $item->expiresAfter(600);

            return $this->createQueryBuilder('n')
                ->select('n.id', 'n.title as value')
                ->where('n.status = 1')
                ->getQuery()
                ->getArrayResult();
        }, 1.0);
    }

}
